<template>
  <el-upload
    list-type="picture-card"
    :class="{ disabled: fileList.length > 0 && imgurl !== '' }"
    :on-preview="handlePictureCardPreview"
    :auto-upload="true"
    :http-request="httpRequest"
    :before-upload="beforeAvatarUpload"
    :file-list="fileList"
    :before-remove="(beforeRemove as any)"
    :on-change="watchRemove"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { Plus } from '@element-plus/icons-vue'

import type {
  UploadProps,
  UploadRequestOptions,
  UploadUserFile,
} from 'element-plus'
import { post } from '@/utils/http/request'
const props = defineProps({
  imgurl: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['photoPath'])
const photoFirstbol = ref(false)
const imgUrl = ref(props.imgurl)
const photoPath = ref()
const fileList = ref<Array<any>>([])
//提交文件表单
const fileOne = ref({
  'Content-Type': 'multipart/form-data',
  satoken: '',
})
//提交文件前的回调
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  fileOne.value.satoken = localStorage.getItem('satoken') as string
  return true
}
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

watch(
  () => props.imgurl,
  (newval) => {
    imgUrl.value = newval
    fileList.value.pop()
    fileList.value.push({ url: newval })
  }
)
//上传文件的请求
const httpRequest = async (e: UploadRequestOptions) => {
  // 构建FormData对象,通过该对象存储要上传的文件
  const formData = new FormData()
  // 遍历当前临时文件List,将上传文件添加到FormData对象中
  formData.append('file', e.file)
  formData.append('cateId', '1')
  const res: any = await post(
    'http://43.139.98.171:3001/admin/qiniu/upload/image',
    formData,
    {
      // 因为我们上传了图片,因此需要单独执行请求头的Content-Type
      headers: fileOne.value,
    }
  )
  photoPath.value = res.data.path

  emit('photoPath', photoPath.value)
}
// 点击图片显示
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const watchRemove = (e: any) => {
  if (imgUrl.value == '') {
    fileList.value.push(e)
    imgUrl.value = '123'
  }
}
const beforeRemove = (e: any) => {
  fileList.value.pop()
  imgUrl.value = ''
}
onMounted(() => {
  imgUrl.value == ''
    ? (fileList.value.pop(), (imgUrl.value = '123'))
    : fileList.value.push({ url: props.imgurl as any })
})
</script>
<style lang="scss">
.disabled .el-upload--picture-card {
  display: none;
}
.el-upload--picture-card {
  width: 100px !important;
  height: 100px !important;
}
</style>
